package com.marvels.financial.loan.service.impl;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.marvels.common.constants.ExtensionFunctionEnum;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.financial.loan.dao.McfeCustomerLoanContractDao;
import com.marvels.financial.loan.dao.McfeLendingProcessDao;
import com.marvels.financial.loan.dao.McfePaymentWithholdDetailDao;
import com.marvels.financial.loan.dao.ReimbursementProcessDao;
import com.marvels.financial.loan.dto.ExtensionFunctionConditionDTO;
import com.marvels.financial.loan.dto.McfeCustomerLoanContractDTO;
import com.marvels.financial.loan.dto.McfeLendingProcess;
import com.marvels.financial.loan.dto.McfePaymentWithholdDTO;
import com.marvels.financial.loan.dto.McfePaymentWithholdDetailDTO;
import com.marvels.financial.loan.dto.PaymentResponse;
import com.marvels.financial.loan.dto.WithholeQueryConditionDTO;
import com.marvels.financial.loan.service.ExtensionFunctionApi;
import com.marvels.financial.loan.service.WithholdPaymentApi;

import net.sf.json.JSONObject;

@Service
public class ExtensionFunctionImpl implements ExtensionFunctionApi{

	@Autowired
	private WithholdPaymentApi withholdPaymentApi;
	
	@Autowired
	private McfeCustomerLoanContractDao mcfeCustomerLoanContractDao;
	
	@Autowired
	private McfePaymentWithholdDetailDao mcfePaymentWithholdDetailDao;
	
	@Autowired
	private McfeLendingProcessDao mcfeLendingProcessDao;
	
	@Autowired
	private ReimbursementProcessDao reimbursementProcessDao;	
	
	@Override
	public PaymentResponse extensionWithhold(ExtensionFunctionConditionDTO conditionDTO)
			throws MarvelsBusinessException {
		String loanId=conditionDTO.getLoanId();
		MarvelsLogUtil.getInstance().info(">>>>>>>>>loanId:"+loanId+",展期代扣请求数据:"+JSONObject.fromObject(conditionDTO));
		if(StringUtils.isEmpty(loanId)){
			throw new MarvelsBusinessException("进件单号不能为空");
		}
		if(StringUtils.isEmpty(conditionDTO.getType())){
			throw new MarvelsBusinessException("展费类型不能为空");
		}
		
		if(StringUtils.isEmpty(conditionDTO.getRequestNo())){
			throw new MarvelsBusinessException("请求编号不能为空");
		}
		McfePaymentWithholdDTO paymentWithholdDTO=new McfePaymentWithholdDTO();
		paymentWithholdDTO.setLoanId(loanId);
		paymentWithholdDTO.setFlowPayType("1");
		paymentWithholdDTO.setTransctionSeq(conditionDTO.getRequestNo());
		paymentWithholdDTO.setWithholdCategory("2");//代扣类别   1扣还款金额    2 扣展期
		
		ExtensionFunctionConditionDTO dto=new ExtensionFunctionConditionDTO();
		dto.setType(conditionDTO.getType());
		dto.setLoanId(loanId);
		dto=selectExtensionInfo(dto);
		paymentWithholdDTO.setExtensionDay(dto.getDay());
		paymentWithholdDTO.setAmount(dto.getAmount());

		McfeCustomerLoanContractDTO contractDTO=mcfeCustomerLoanContractDao.selectContractByLoanId(conditionDTO.getLoanId());
		paymentWithholdDTO.setBankHeadLink(contractDTO.getPaymentBankHead());
		
		
		String type=conditionDTO.getWithholdWay();
		paymentWithholdDTO.setType(type);
		if("1".equals(type)){//四要素代扣
			paymentWithholdDTO.setCustName(conditionDTO.getS1PayerName());
			paymentWithholdDTO.setCustCardNo(conditionDTO.getS3PayerCardNo());
			paymentWithholdDTO.setBankName(conditionDTO.getBankName());
			paymentWithholdDTO.setBankCardNo(conditionDTO.getS4PayerBankCardNo());
			paymentWithholdDTO.setMobile(conditionDTO.getS7BankMobile());
			paymentWithholdDTO.setT2SmsCode(conditionDTO.getT2SmsCode());
		}else{
			paymentWithholdDTO.setBankCardNo(contractDTO.getPaymentAcctNo());
			paymentWithholdDTO.setBankName(contractDTO.getPaymentBankName());
			paymentWithholdDTO.setCustCardNo(contractDTO.getCustCardNo());
		}
		PaymentResponse response=withholdPaymentApi.withholdCommonDeal(paymentWithholdDTO);
		MarvelsLogUtil.getInstance().info(">>>>>>>>>loanId:"+conditionDTO.getLoanId()+",展期代扣返回结果:"+JSONObject.fromObject(response));
		return response;
	}

	@Override
	public PaymentResponse extensionWithholdQuery(ExtensionFunctionConditionDTO conditionDTO)
			throws MarvelsBusinessException {
		MarvelsLogUtil.getInstance().info(">>>>>>>>>loanId:"+conditionDTO.getLoanId()+",展期代扣结果查询请求数据:"+JSONObject.fromObject(conditionDTO));
		String requestNo=conditionDTO.getRequestNo();
		//先查询数据库中状态
		McfePaymentWithholdDetailDTO detailDTO=mcfePaymentWithholdDetailDao.selectByReqNo(requestNo);
		String status=detailDTO.getStatus();
		PaymentResponse response=new PaymentResponse();
		if(status.equals("2")){//成功
			response.setCode("0");
			response.setMsg("成功");
		}else if(status.equals("9")){//失败
			response.setCode("-1");
			response.setMsg(detailDTO.getRtnResponseMsg());
		}else{//调用第三方
			try {
				WithholeQueryConditionDTO queryConditionDTO = new WithholeQueryConditionDTO();
				queryConditionDTO.setFundSource(detailDTO.getFundCode());
				queryConditionDTO.setLoanId(detailDTO.getLoanId());
				queryConditionDTO.setOrderNumber(detailDTO.getRtnOrderNo());
				queryConditionDTO.setReqNo(detailDTO.getTransctionSeq());
				MarvelsLogUtil.getInstance().info(">>>>>>>>loanId" + detailDTO.getLoanId()+ "第三方代扣结果查询请求参数:"+JSONObject.fromObject(queryConditionDTO));
				response = withholdPaymentApi.withholdPaymentQuery(queryConditionDTO);
				MarvelsLogUtil.getInstance().info(">>>>>>>>loanId" + detailDTO.getLoanId()+ "第三方代扣结果查询返回结果:"+JSONObject.fromObject(response));
			} catch (Exception e) {
				response.setCode("1");
				response.setMsg("处理中");
				MarvelsLogUtil.getInstance().error(">>>>>>>>loanId" + detailDTO.getLoanId()+ "代扣结果查询异常:", e);
			}
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>>loanId:"+conditionDTO.getLoanId()+",展期代扣结果查询返回结果:"+JSONObject.fromObject(response));
		return response;
	}

	@Override
	public List<McfePaymentWithholdDetailDTO> extensionRecordsQuery(ExtensionFunctionConditionDTO conditionDTO)
			throws MarvelsBusinessException {
		List<McfePaymentWithholdDetailDTO> list=mcfePaymentWithholdDetailDao.list(conditionDTO.getLoanId(), "2");
		return list;
	}

	@Override
	public ExtensionFunctionConditionDTO selectExtensionInfo(ExtensionFunctionConditionDTO conditionDTO)
			throws MarvelsBusinessException {
		String loanId=conditionDTO.getLoanId();
		String type=conditionDTO.getType();
		if(StringUtils.isEmpty(loanId)){
			throw new MarvelsBusinessException("loanId不能为空");
		}
		if(StringUtils.isEmpty(type)){
			throw new MarvelsBusinessException("类别不能为空");
		}
		ExtensionFunctionConditionDTO dto=new ExtensionFunctionConditionDTO();
		ExtensionFunctionEnum[] extensionlist=ExtensionFunctionEnum.enums();
		for(ExtensionFunctionEnum extensionFunctionEnum:extensionlist){
			if(conditionDTO.getType().equals(extensionFunctionEnum.getType())){
				dto.setDay(extensionFunctionEnum.getDay());
				McfeLendingProcess mcfeLendingProcess=mcfeLendingProcessDao.selectByloanIdAndStatus(loanId, "");
				List<Map> list = reimbursementProcessDao.queryReturnInfoByLoanId(loanId);
				if(mcfeLendingProcess==null || CollectionUtils.isEmpty(list)){
					throw new MarvelsBusinessException("放款申请信息不存在");
				}
				BigDecimal amount=new BigDecimal(extensionFunctionEnum.getValue()).multiply(mcfeLendingProcess.getPrincipalAmtAct());
				if(null!=list.get(0) && null != list.get(0).get("fine")){
					BigDecimal fineAmount = BigDecimal.ZERO;
					if(list.get(0).get("fine") instanceof BigDecimal){
						fineAmount = (BigDecimal)list.get(0).get("fine");
					}else{
						try{
						String fine = list.get(0).get("fine").toString();
						fineAmount = new BigDecimal(fine);
						}catch(Exception ex){
							MarvelsLogUtil.getInstance().error("selectExtensionInfo 获取滞纳金异常", ex);
						}
					}
					amount = amount.add(fineAmount);
				}
				dto.setAmount(amount);
				break;
			}
		}
		return dto;
	}
}
